#include "ble_helper.h"
#ifdef __USER_BLE_CONN__
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
ble_write_callback_t write_callback = 0;
class BLECallback : public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string rxValue = pCharacteristic->getValue();
    if (write_callback != 0) {
      write_callback(rxValue);
    }
  }
  void onRead(BLECharacteristic *pCharacteristic) {
    pCharacteristic->setValue("XXX");
  }
};
class MyBLEServerCallbacks : public BLEServerCallbacks {
  void onConnect(BLEServer *pServer) {
    printf("BLE connected\n");
     BLEDevice::stopAdvertising();
  }
  void onDisconnect(BLEServer *pServer) {
    printf("BLE disconnect\n");
     BLEDevice::startAdvertising();
  }
};
MyBLEServerCallbacks server_callbacks;
BLECallback callback;
void init_ble(ble_write_callback_t cb) {
  write_callback = cb;
  BLEDevice::init("ESP32-Car");
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(&server_callbacks);
  BLEService *pService = pServer->createService(SERVICE_UUID); 
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
      CHARACTERISTIC_UUID,
      BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);

  pCharacteristic->setCallbacks(&callback);
  pCharacteristic->setValue("Hello World says Neil");
  pService->start();
  // BLEAdvertising *pAdvertising = pServer->getAdvertising();  // this still is
  // working for backward compatibility
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(
      0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);

  BLEDevice::startAdvertising();
}
#endif